﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace GeoParser
{
	/// <summary>
	/// Represents a GPS track (log of positions).
	/// </summary>
	[Immutable]
	public class Track
	{
		private readonly XElement m_Element;

		public Track(XElement element)
		{
			if (element == null)
				throw new ArgumentNullException("element");
			m_Element = element;
		}
	
		public IEnumerable<TrackSegment> Segments
		{
			get
			{
				return m_Element.Elements(m_Element.Name.Namespace + "trkseg")
					.Select(x => new TrackSegment(x));
			}
		}

		public Distance Length
		{
			get
			{
				var tot = new Distance();
				foreach (TrackSegment segment in Segments)
					tot += segment.Length;
				return tot;
			}
		}

		public TimeSpan Time
		{
			get
			{
				var tot = new TimeSpan();
				foreach (TrackSegment segment in Segments)
					tot += segment.Time;
				return tot;
			}
		}

		public Distance LengthBetween(GeoPoint start, GeoPoint end)
		{
			var points = Segments.SelectMany(x => x.Points);

			return Distance.Length(points.Cast<GeoPoint>()
				.SkipWhile(x => !GeoPoint.Equals(x, start))
				.TakeWhile(x => !GeoPoint.Equals(x, end)));
		}

		public TimeSpan TimeBetween(GeoPoint start, GeoPoint end)
		{
			var points = Segments.SelectMany(x => x.Points)
				.SkipWhile(x => !GeoPoint.Equals(x, start))
				.TakeWhile(x => !GeoPoint.Equals(x, end));

			return points.Last().Time - points.First().Time;
		}
	}
}